package com.zx._07_数据库.jdbc;

import com.github.javafaker.Faker;
import com.zx.common.entity.UserData;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class 造数据_分区表 {

    private static final ExecutorService pool = Executors.newFixedThreadPool(10);
    private static final Faker faker = new Faker(Locale.CHINA);

    public static void main(final String[] args) throws Exception {
        final String sql = Mate.getInsertSqlPartition();
        AtomicLong al = new AtomicLong(0);
        pool.execute(() -> {
            // 每个批次1000
            int batchSize = 5000;
            // 批次数量
            int batchNum = Mate.TABLE_SIZE / batchSize;
            Connection con = JDBC.getConnection();
            PreparedStatement ps;
            try {
                ps = con.prepareStatement(sql);
                for (int i = 0; i < batchNum; i++) {
                    // 分批执行，1000一个提交
                    List<UserData> list = buildData(batchSize, al);
                    for (UserData user : list) {
                        ps.setLong(1, user.getId());
                        ps.setString(2, user.getRealName());
                        ps.setString(3, user.getCellPhone());
                        ps.setString(4, user.getUniversityName());
                        ps.setString(5, user.getCity());
                        ps.setString(6, user.getStreet());
                        ps.addBatch();
                    }
                    //执行批！
                    ps.executeBatch();
                    log.info("table insert ing, index={}, 进度={}", al.get(), (int) (100D * i / batchNum));
                }
            } catch (final SQLException e) {
                e.printStackTrace();
            }
        });

        pool.shutdown();
    }

    public static List<UserData> buildData(int num, AtomicLong al) {
        List<UserData> resList = Stream
                .iterate(1, i -> i + 1).limit(num)
                .map(i -> {
                    final UserData userInfo = new UserData();
                    userInfo.setId(al.getAndAdd(Mate.TABLE_NUM));
                    userInfo.setRealName(faker.name().fullName());
                    userInfo.setCellPhone(faker.phoneNumber().cellPhone());
                    userInfo.setCity(faker.address().city());
                    userInfo.setStreet(faker.address().streetAddress());
                    userInfo.setUniversityName(faker.university().name());
                    return userInfo;
                }).collect(Collectors.toList());
        return resList;
    }


}



